package com.yn.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.yn.common.exception.TransitException;
import com.yn.common.model.system.SystemCity;
import com.yn.common.model.zyorder.ZyOrderServiceT;
import com.yn.common.model.zyorder.ZyServiceConfig;
import com.yn.common.model.zyorder.ZyServiceRegionPrice;
import com.yn.common.request.sc.PageParamRequest;
import com.yn.common.request.sc.SystemCitySearchRequest;
import com.yn.common.request.zyorder.ZyServiceRegionPriceRequest;
import com.yn.common.request.zyorder.ZyServiceRegionPriceSearch;
import com.yn.common.response.zyorder.ZyServiceRegionPriceResponse;
import com.yn.common.utils.CommonUtil;
import com.yn.common.utils.ExceptionUtil;
import com.yn.service.dao.zy.ZyServiceRegionPriceDao;
import com.yn.service.service.UserService;
import com.yn.service.service.ZyOrderServiceService;
import com.yn.service.service.ZyServiceRegionPriceService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 转运订单 接口实现
 */
@Service
public class ZyServiceRegionPriceServiceImpl extends ServiceImpl<ZyServiceRegionPriceDao, ZyServiceRegionPrice> implements ZyServiceRegionPriceService {

    private Logger logger = LoggerFactory.getLogger(ZyServiceRegionPriceServiceImpl.class);
    @Autowired
    private ZyServiceConfigServiceImpl zyServiceConfigServiceImpl;

    @Autowired
    private SystemCityServiceImpl systemCityServiceImpl;

    @Autowired
    private ZyServiceRegionPriceDao zyServiceRegionPriceDao;

    @Autowired
    private ZyOrderServiceService zyOrderServiceService;

    @Autowired
    private UserService userService;


    @Override
    public Boolean saveOrUpdateServiceRegionPrice(ZyServiceRegionPriceRequest zyServiceRegionPriceRequest) {
        boolean b = repeatVerification(zyServiceRegionPriceRequest);
        if (!b) {
            logger.error("该区域服务项配置已存在：{}", zyServiceRegionPriceRequest);
            throw new TransitException("该区域服务项配置已存在");
        }
        Integer userId = userService.getUserId();
        ZyServiceRegionPrice zyServiceRegionPrice = new ZyServiceRegionPrice();
        BeanUtils.copyProperties(zyServiceRegionPriceRequest, zyServiceRegionPrice);
        zyServiceRegionPrice.setCreateId(userId);
        return this.saveOrUpdate(zyServiceRegionPrice);
    }

    @Override
    public ZyServiceRegionPriceResponse getServiceRegionPrice(Integer id) {
        ZyServiceRegionPrice zyServiceRegionPrice = this.getById(id);
        if (zyServiceRegionPrice == null) {
            logger.error("配置区域信息不存在：{}", id);
            throw new TransitException("配置区域信息不存在");
        }

        ZyServiceRegionPriceResponse zyServiceRegionPriceResponse = new ZyServiceRegionPriceResponse();
        BeanUtils.copyProperties(zyServiceRegionPrice, zyServiceRegionPriceResponse);
        Integer serviceConfigId = zyServiceRegionPrice.getServiceConfigId();
        Boolean notEmpty = CommonUtil.isNotEmpty(serviceConfigId);
        if (notEmpty) {
            ZyServiceConfig zyServiceConfig = zyServiceConfigServiceImpl.getById(serviceConfigId);
            ExceptionUtil.checkBooleanException(CommonUtil.isEmpty(zyServiceConfig), "配置信息有误", "zyServiceConfig");
            String serviceName = zyServiceConfig.getServiceName();
            zyServiceRegionPriceResponse.setServiceConfigName(serviceName);
        }
        String regionCode = zyServiceRegionPrice.getRegionCode();
        if (StringUtils.isNotEmpty(regionCode)) {
            LambdaQueryWrapper<SystemCity> systemCityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            systemCityLambdaQueryWrapper.eq(SystemCity::getAreaCode, regionCode);
            SystemCity one = systemCityServiceImpl.getOne(systemCityLambdaQueryWrapper);
            ExceptionUtil.checkBooleanException(CommonUtil.isEmpty(one), "配置信息有误", "systemCityServiceImpl");
            zyServiceRegionPriceResponse.setRegionCodeName(one.getMergerName());
        }
        Integer regionRangePrice = zyServiceRegionPrice.getRegionRangePrice();
        if (regionRangePrice != null && regionRangePrice > 0) {
            zyServiceRegionPriceResponse.setRegionRangePrice(regionRangePrice / 100);
        }
        Integer unitPrice = zyServiceRegionPrice.getUnitPrice();
        if (unitPrice != null && unitPrice > 0) {
            zyServiceRegionPriceResponse.setUnitPrice(unitPrice / 100);
        }
        Integer commissionMoney = zyServiceRegionPrice.getCommissionMoney();
        if (commissionMoney != null && commissionMoney > 0) {
            zyServiceRegionPriceResponse.setCommissionMoney(commissionMoney / 100);
        }
        return zyServiceRegionPriceResponse;
    }

    @Override
    public void del(Integer id) {
        LambdaQueryWrapper<ZyOrderServiceT> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(ZyOrderServiceT::getServiceConfigId, id);
        queryWrapper1.eq(ZyOrderServiceT::getIsDelTag, false);
        List<ZyOrderServiceT> zyOrderServiceTList = zyOrderServiceService.list(queryWrapper1);
        if (CollectionUtils.isNotEmpty(zyOrderServiceTList)) {
            logger.error("该服务项配置下存在订单服务,不能删除 配置id:{}", id);
            throw new TransitException("该服务项配置下存在订单服务信息，不能删除");
        }
        this.removeById(id);
    }

    @Override
    public List<ZyServiceRegionPriceResponse> listServiceRegionPriceList(ZyServiceRegionPriceSearch zyServiceRegionPriceSearch,
                                                                         PageParamRequest pageParamRequest) {
        String regionCode = zyServiceRegionPriceSearch.getRegionCode();
        String appRegionCode = zyServiceRegionPriceSearch.getAppRegionCode();
        Set<String> cityRegionCodes = new HashSet<>();
        if (StringUtils.isNotEmpty(regionCode)) {
            List<SystemCity> systemCityList = new ArrayList<>();
            SystemCity systemCity = systemCityServiceImpl.getCityByAreaCode(regionCode);
            if (systemCity == null) {
                throw new TransitException("区域信息不存在!");
            }
            systemCityList.add(systemCity);
            cityRegionCodes.add(systemCity.getAreaCode());
            while (CollectionUtils.isNotEmpty(systemCityList)) {
                List<SystemCity> systemCitys = new ArrayList<>();
                systemCityList.parallelStream().forEach(p -> {
                    Integer cityId = p.getCityId();
                    SystemCitySearchRequest request = new SystemCitySearchRequest();
                    request.setParentId(cityId);
                    Object list = systemCityServiceImpl.getList(request);
                    if (CommonUtil.isNotEmpty(list)) {
                        systemCitys.addAll((List<SystemCity>) list);
                    }
                    cityRegionCodes.add(p.getAreaCode());
                });
                if (CollectionUtils.isEmpty(systemCitys)) {
                    systemCityList = null;
                }else {
                    systemCityList = systemCitys;
                }
            }
        }

        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        if(StringUtils.isNotEmpty(appRegionCode)){
            cityRegionCodes.add(appRegionCode);
        }
        zyServiceRegionPriceSearch.setRegionCodeSet(cityRegionCodes);
        List<ZyServiceRegionPriceResponse> list = zyServiceRegionPriceDao.listZyServiceRegionPrice(zyServiceRegionPriceSearch);
        if (CollectionUtils.isNotEmpty(list)) {
            list.parallelStream().forEach(p -> {
                Integer regionRangePrice = p.getRegionRangePrice();
                if (regionRangePrice != null && regionRangePrice > 0) {
                    p.setRegionRangePrice(regionRangePrice / 100);
                }
                Integer unitPrice = p.getUnitPrice();
                if (unitPrice != null && unitPrice > 0) {
                    p.setUnitPrice(unitPrice / 100);
                }
                Integer commissionMoney = p.getCommissionMoney();
                if (commissionMoney != null && commissionMoney > 0) {
                    p.setCommissionMoney(commissionMoney / 100);
                }
            });
        }

        return list;
    }


    //重复验证
    public boolean repeatVerification(ZyServiceRegionPriceRequest zyServiceRegionPriceRequest) {
        Integer id = zyServiceRegionPriceRequest.getId();
        LambdaQueryWrapper<ZyServiceRegionPrice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZyServiceRegionPrice::getServiceConfigId, zyServiceRegionPriceRequest.getServiceConfigId());
        queryWrapper.eq(ZyServiceRegionPrice::getRegionCode, zyServiceRegionPriceRequest.getRegionCode());
        ZyServiceRegionPrice one = this.getOne(queryWrapper);
        if (one != null) {
            if (id == null) {
                return false;
            }
            if (!id.equals(one.getId())) {
                return false;
            }
        }
        return true;
    }
}

